 package org.zlb.netty.client.serial;

import org.zlb.netty.proto.SubReqProto;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class SubReqProtoClientHandler extends ChannelInboundHandlerAdapter {
    
    public SubReqProtoClientHandler() {
    }
    
    public SubReqProtoClientHandler(SubReqProtoClient client) {
        this.client = client;
    }
    
    public SubReqProtoClientHandler(String host, int port) {
        this.client = new SubReqProtoClient(host, port);
    }

    private SubReqProtoClient client;
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i=0; i<10; i++) {
            SubReqProto.SubReq.Builder build = SubReqProto.SubReq.newBuilder();
            build.setSubReqId(i);
            build.setUserName("zlb");
            build.setUserPhone("13512345678");
            build.setAddress("湖南省长沙市望城区");
            
            ctx.write(build.build());
        }
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        client.connect(); // 断开重连处理 
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                
            } else if (state == IdleState.WRITER_IDLE) {
                SubReqProto.SubReq.Builder build = SubReqProto.SubReq.newBuilder();
                build.setSubReqId(0);
//                ctx.channel().writeAndFlush(build.build());
//                System.out.println("发送心跳测试");
            } else {
                System.out.println("ALL_IDLE");
            } 
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
